﻿using System;
using System.ComponentModel;
using System.IO;
using System.Net;
using System.Windows.Forms;
using TestApp.Util;
using System.Collections.Generic;

namespace TestApp
{
    public partial class FormExamples : Form
    {
        static MatrixCollection matrices;

        const string base_url = "http://www.cise.ufl.edu/research/sparse/MM/{0}/{1}.tar.gz";

        public string FileName { get; private set; }

        WebClient downloader;
        MatrixInfo selectedMatrix;

        public FormExamples()
        {
            InitializeComponent();
        }

        private void FormExamples_Load(object sender, EventArgs e)
        {
            if (matrices == null)
            {
                matrices = MatrixCollection.LoadDefault();
            }

            FillListView(matrices.Items);
        }

        private void listView1_SelectedIndexChanged(object sender, EventArgs e)
        {
            var items = listView1.SelectedItems;

            if (items != null && items.Count == 1)
            {
                selectedMatrix = items[0].Tag as MatrixInfo;
                FileName = selectedMatrix.Name + ".mtx";

                bool exists = File.Exists(FileName);
                btnOk.Enabled = exists;

                // Check if an archive file exists.
                if (!exists && File.Exists(Path.ChangeExtension(FileName, ".tar.gz")))
                {
                    btnDownload.Text = "Unpack";
                    btnDownload.Enabled = true;
                }
                else
                {
                    btnDownload.Text = "Download";
                    btnDownload.Enabled = !exists;
                }
            }
        }

        private void FillListView(IEnumerable<MatrixInfo> list)
        {
            var items = new List<ListViewItem>();

            foreach (var matrix in list)
            {
                items.Add(new ListViewItem(matrix.ToArray()) { Tag = matrix });
            }

            listView1.Items.Clear();
            listView1.Items.AddRange(items.ToArray());
        }

        #region Download

        private void btnDownload_Click(object sender, EventArgs e)
        {
            if (btnDownload.Text == "Download")
            {
                if (selectedMatrix != null && !File.Exists(FileName))
                {
                    string url = String.Format(base_url, selectedMatrix.Group, selectedMatrix.Name);

                    btnCancel.Enabled = false;
                    btnDownload.Text = "Cancel";
                    DownloadFile(url, Path.ChangeExtension(FileName, ".tar.gz"));
                }
            }
            else if (btnDownload.Text == "Cancel")
            {
                if (downloader != null)
                {
                    btnCancel.Enabled = true;
                    btnDownload.Text = "Download";
                    downloader.CancelAsync();
                    progressBar1.Value = 0;
                }
            }
            else if (btnDownload.Text == "Unpack")
            {
                try
                {
                    Helper.UnpackFile(Path.ChangeExtension(FileName, ".tar.gz"), FileName);
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }

                btnOk.Enabled = true;
                btnCancel.Enabled = true;
                btnDownload.Enabled = false;
            }
        }

        void DownloadFile(string url, string targetFile)
        {
            downloader = new WebClient();
            downloader.Proxy = null;
            downloader.DownloadProgressChanged += new DownloadProgressChangedEventHandler(ProgressChanged);
            downloader.DownloadFileCompleted += new AsyncCompletedEventHandler(Completed);

            downloader.DownloadFileAsync(new Uri(url), targetFile);
        }

        void ProgressChanged(object sender, DownloadProgressChangedEventArgs e)
        {
            progressBar1.Value = e.ProgressPercentage;
        }

        void Completed(object sender, AsyncCompletedEventArgs e)
        {
            if (e.Error != null)
            {
                if (e.Error.InnerException != null)
                {
                    MessageBox.Show(e.Error.InnerException.Message);
                }
                else
                {
                    MessageBox.Show(e.Error.Message);
                }
            }
            else if (e.Cancelled)
            {
            }
            else
            {
                try
                {
                    Helper.UnpackFile(Path.ChangeExtension(FileName, ".tar.gz"), FileName);
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
            }

            progressBar1.Value = 0;

            btnOk.Enabled = true;
            btnCancel.Enabled = true;
            btnDownload.Enabled = false;
            btnDownload.Text = "Download";
        }

        #endregion
    }
}
